package config

import (
	"net"
	"fmt"
	"log"
	"code.google.com/p/cloud9lib/restc"
)

type Redirect struct {
	Pattern string
	Target string
}

type Proxy struct {
	Pattern string
	Target string
}

type FileServer struct {
	Pattern string
	Path string
}

type HTTPConfig struct {
	APIBaseURL string
	APIPattern string
	Redirects []Redirect
	Proxies []Proxy
	FileServers []FileServer
}

type Host struct {
	URL string	
}

type Graph struct {
	ID string
	Capacity int
}

type GraphConfig struct {
	Graphs []Graph
}

type Node struct {
	Target string
}

type ClusterConfig struct {
	Nodes []Node
}

type Config struct {
	HTTPConfig HTTPConfig
	GraphConfig GraphConfig
	ClusterConfig ClusterConfig
}

type Slave struct {
	Addr string
}

type Params struct {
	block string
}

var Local Config

// master: ip and port of graphd instance with config info
func LoadFromMaster(master string) {

	err := restc.Get("http://" + master + "/FEEDGRAPH/CONFIG", nil, &Local)

	log.Println(Local)
	
	if err != nil {
		panic(err)
	}
}

func LocalIP() (net.IP, error) {

	addrs, _ := net.InterfaceAddrs()
	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok {

                        v4 := ipnet.IP.To4() 
                        if v4 == nil || v4[0] == 127 {
				// loopback address 
                                continue 
                        }

			return v4, nil
		}
	}

	return nil, fmt.Errorf("could not find local IP address")
}

func RegisterSlave(master, slave string) {

	err := restc.Post("http://" + master + "/FEEDGRAPH/SLAVES/registered", nil, Slave{slave})

	if err != nil {
		panic(err)
	}
}

func WaitForMaster(master string) {

	params := Params{block:"true"}

	err := restc.Get("http://" + master + "/FEEDGRAPH/MASTER/ready", params, &[]struct{}{})

	if err != nil {
		panic(err)
	}
}
